package com.jsd.demo1;

/**
 * @author jsd
 */
public class A {

    public static void main(String[] args) {
        B b = new B();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    b.inNumber();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "生成者A").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    b.inNumber();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "生成者B").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    b.deNumber();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "消费者C").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    b.deNumber();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "消费者D").start();
    }
}

class B {

    private int number = 0;

    public synchronized void inNumber () throws InterruptedException {
        while (number != 0) {
            wait();
        }

        number++;
        System.out.println(Thread.currentThread().getName() + "=>生成了" + number + "个");
        notifyAll();
    }

    public synchronized void deNumber () throws InterruptedException {
        while (number == 0) {
            wait();
        }
        number--;
        System.out.println(Thread.currentThread().getName() + "=>还剩下" + number + "个");
        notifyAll();
    }

}
